package com.dxy.hms.base;

import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {


    @ExceptionHandler(UnifiedException.class)
    public Resp unifiedException(UnifiedException ex) {
        log.error("发生业务异常, code: {}, msg: {}", ex.getStatus(), ex.getMsg());
        return Resp.bizFail(ex);
    }

    @ExceptionHandler(JwtException.class)
    public Resp jwtException(JwtException ex) {
        log.error("发生jwt异常,msg: {}", ex.getMessage());
        return Resp.bizFail(StatusMessageEnum.JWT_TOKEN_ERROR);
    }

    @ExceptionHandler({Exception.class})
    public Resp exception(Exception ex) {
        log.error("系统异常：", ex);
        return Resp.bizFail(StatusMessageEnum.UNDEFINED.getStatus(), defaultMessage(ex));
    }

    private String defaultMessage(Throwable t) {
        return t.getClass().getSimpleName() + (t.getMessage() == null ? "" : ": " + t.getMessage());
    }


}